/*
 * UpdateDatabaseListActivity.java
 *
 * Copyright(c) 2011
 * Michael Kroez
 * kroez@studiorutton.de
 *
 * All rights reserved.
 *
 * $Id$
 * 
 */

package de.studiorutton.gerengdic.update;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import de.studiorutton.access.FileAccess;
import de.studiorutton.access.FileAccessException;
import de.studiorutton.access.Result;
import de.studiorutton.colorschemes.IColorSchemeMapper;
import de.studiorutton.gerengdic.LearningWordsActivity;
import de.studiorutton.gerengdic.Prefs;
import de.studiorutton.gerengdic.R;
import de.studiorutton.gerengdic.dictionary.DictionaryActivity;
import de.studiorutton.gerengdic.indexeddictionary.IndexedDictionaryActivity;
import de.studiorutton.gerengdic.library.LibraryDatabase;

public class UpdateDatabaseListActivity extends ListActivity implements IUpdateDatabaseListener, OnClickListener {
	private static final String TAG = "learningwords";

	private UpdateDatabase ud;
	private MyTaskEventListener mtel;
	
	private ProgressBar pb;
	private Button buttonExecute, buttonCancel, buttonCheck;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Log.d(TAG, "UpdateDatabaseListActivity: starting onCreate");
		setContentView(R.layout.updatedatabase);
	}
	
	public void onStart() {
		super.onStart();
		// Log.d(TAG, "UpdateDatabaseListActivity: starting onResume");
		ud = UpdateDatabase.get();

		buttonExecute = (Button) findViewById(R.id.executedownload);
		buttonExecute.setOnClickListener(this);

		buttonCheck = (Button) findViewById(R.id.checkfornewer);
		buttonCheck.setOnClickListener(this);
		
		buttonCancel = (Button) findViewById(R.id.canceldownload);
		buttonCancel.setOnClickListener(this);

		pb = (ProgressBar) findViewById(R.id.downloadprogress);
		
		IColorSchemeMapper csmi = Prefs.getInstance().getColorSchemeMapper();
		RelativeLayout rootrl = (RelativeLayout) findViewById( R.id.download );
		rootrl.setBackgroundColor( csmi.getBackgroundColor() );
		
		RelativeLayout rl = (RelativeLayout) findViewById( R.id.title );
		rl.setBackgroundDrawable( csmi.getTitleStyle().getUpdateTitleBackground() );
		getListView().setDivider( csmi.getListDividerDrawable());
		TextView title = (TextView) findViewById( R.id.downloadtitle );
		title.setTextColor( csmi.getTitleStyle().getUpdateTitleTextcolor());
				
		if ( !checkDatabase()) {
			buttonCheck.setVisibility( View.INVISIBLE );
		}
	}
	
	public void onResume() {
		super.onResume();
		// Log.d(TAG, "UpdateDatabaseListActivity: starting onStart");
		mtel = new MyTaskEventListener();
		ud.setEventListener( mtel );

		updateProgressMode();
		updateUpdateListView();
	}
	
	public void onPause() {
		super.onPause();
		
		if (isFinishing()) {
			ud.setEventListener( null );
			ud.cancelTasks();
			UpdateDatabase.release();
			ud = null;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if(!checkDatabase())
			return false;
	
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.updatedatabasemenu, menu);
		return true;
	}
	
	protected void updateProgressMode() {
		if (ud.isRunning()) {
			pb.setVisibility(View.VISIBLE);
			buttonExecute.setEnabled(false);
			buttonCheck.setEnabled( false );
			buttonCancel.setEnabled(true);
		} else {
			pb.setVisibility(View.INVISIBLE);
			buttonExecute.setEnabled(true);
			buttonCheck.setEnabled( true );
			buttonCancel.setEnabled( false );
		}
	}
	
	protected void updateUpdateListView() {
		UpdateDatabaseAdapter uda = ud.getUpdateDatabaseAdapter( this );
		setListAdapter( uda );
	}
	
	public boolean checkDatabase() {
		try {
			FileAccess.checkExistsAndReadable(LibraryDatabase.get().getFileLocation(LibraryDatabase.DE_EN_DICT));
		} catch (FileAccessException fe) {
			return false;
		}
		return true;
	}
	
	@Override
	public void onClick( View view ) {
		int id = view.getId();
		
		switch( id ) {
		case R.id.executedownload:
			ud.runTasks( false );
			updateProgressMode();
			break;
		case R.id.checkfornewer:
			ud.runTasks( true );
			updateProgressMode();
			break;
		case R.id.canceldownload:
			setResult(LearningWordsActivity.DATABASE_UPDATE_CANCELED);
			// Log.d(TAG, "UpdateDatabaseActivity: returning to main screen.");
			ud.cancelTasks();
			updateProgressMode();
			break;
		default:
			; // nothing;
			
		}
	}
	
	protected void showNotificationDialog(final Result res) {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				UpdateDatabaseListActivity.this);
		builder.setTitle(
				getResources().getString(R.string.notification))
				.setMessage(res.getLocalizedMessage())
				.setCancelable(false)
				.setPositiveButton(getResources().getString(R.string.okay),
						new android.content.DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								updateProgressMode();
								setResult( LearningWordsActivity.DATABASE_UPDATE_CANCELED );
								
							}
						});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	class MyTaskEventListener implements IUpdateTaskEventListener {

		public void notifyTaskEnded(Result res) {
			
			updateProgressMode();
			
			if ( res == null ) {
				return;
			}
			if (res.isError() || res.isCancelled()) {
				showNotificationDialog(res);
				return;
			}

			if (ud.getCrrDownloadTask() == ud.getUpdateDatabaseSize() - 1) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						UpdateDatabaseListActivity.this);

				android.content.DialogInterface.OnClickListener mInfoOnClickListener = new android.content.DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						setResult(LearningWordsActivity.DATABASE_UPDATE_OK);
						finish();
					}

				};

				builder.setMessage(
						getResources().getString(R.string.download_done))
						.setCancelable(false)
						.setPositiveButton(
								getResources().getString(R.string.okay),
								mInfoOnClickListener);
				AlertDialog alert = builder.create();
				alert.show();
			}
		}

		public void notifyNewer(Result res) {
			updateProgressMode();

			if ( res == null )
				return;
			showNotificationDialog(res);
			return;
		}
	}

	public static final int DATABASE_UPDATE = 10;
	public static final int DICTIONARY_RUN = 20;
	public static final int HISTORY = 30;

	public static final int DATABASE_UPDATE_CANCELED = 1;
	public static final int DATABASE_UPDATE_OK = 2;
	public static final int DICTIONARY_RETURN = 3;

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		Intent i;
		switch (item.getItemId()) {
		case R.id.menudictionary:
			i = new Intent(getApplicationContext(), DictionaryActivity.class);
			startActivityForResult(i, DICTIONARY_RUN);
			return true;
		case R.id.menuindexeddictionary:
			i = new Intent(getApplicationContext(),
					IndexedDictionaryActivity.class);
			startActivityForResult(i, DICTIONARY_RUN);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	public MyTaskEventListener getEventListener() {
		return mtel;
	}
	
	public Context getContext() {
		return this;
	}
}
